//
//  GiftsViewController.m
//  SeaMelonSeeds_Counselor
//
//  Created by 尤振宇 on 2017/7/14.
//  Copyright © 2017年 杨笑. All rights reserved.
//

#import "GiftsViewController.h"
#import "SendMessageViewController.h"
#import "GiftsTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "InfoApi.h"

@interface GiftsViewController ()<EaseMessageViewControllerDelegate,EaseMessageViewControllerDataSource,EMChatManagerDelegate>
{
    UITextField *_textField;
}

@end

@implementation GiftsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationItem.rightBarButtonItem = [Tool BarButtonItemWithTitle:@"发送" target:self action:@selector(send)];
    [self.tableView registerCellWithNib:@"GiftsTableViewCell"];
    [self configNotDataView:[UIImage imageNamed:@"noNotice"] text:@"暂无密信"];
}

-(void)send
{
    UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"提示" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    [vc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        _textField = textField;
    }];
    [vc addAction:[UIAlertAction actionWithTitle:@"OK" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        SendMessageViewController *chatController = [[SendMessageViewController alloc] initWithConversationChatter:_textField.text conversationType:EMConversationTypeChat];
        chatController.delegate = self;
        chatController.dataSource = self;
        [self.navigationController pushViewController:chatController animated:YES];
    }]];
    [self presentViewController:vc animated:YES completion:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadData];
    [[AppDelegate sharedApplication].rootTabBarController setupUnreadMessageCount];
}

-(void)loadData
{
    WeakSelf(self)
//    dispatch_queue_t systemQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
//    dispatch_async(systemQueue, ^{
//        
        NSMutableArray *requestArr = [NSMutableArray array];
        NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
        [weakself.dataArray removeAllObjects];

        for (EMConversation *conv in conversations) {
            [requestArr addObject:@{@"hx_username":conv.conversationId}];
            
            UserInfo *info = [UserInfo new];
            info.conversation = conv;
            [weakself.dataArray addObject:info];
        }
    
        if (requestArr.count == 0) {
            return;
        }
    
        InfoApi *infoApi = [[InfoApi alloc]initWithUserIDs:requestArr];
        [infoApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            if (kCode(request.responseJSONObject)) {
                
                for (NSDictionary *dic in [request.responseJSONObject objectForKey:@"data"]) {
                    for (UserInfo *info in weakself.dataArray) {
                        if ([info.conversation.conversationId isEqualToString:[dic objectForKey:@"hx_username"]]) {
                            [info setValuesForKeysWithDictionary:dic];
                        }
                    }
                }
            }
            
//            dispatch_async(dispatch_get_main_queue(), ^{
                [weakself showOrHideDataView];
                [weakself.tableView reloadData];
//            });
            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
//            dispatch_async(dispatch_get_main_queue(), ^{
                [weakself showOrHideDataView];
                [weakself.tableView reloadData];
//            });
        }];
//    });

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    GiftsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GiftsTableViewCell" forIndexPath:indexPath];
    
    UserInfo *info = self.dataArray[indexPath.row];
    EMConversation *conversation = info.conversation;
    EaseMessageModel *model = [[EaseMessageModel alloc]initWithMessage:conversation.latestMessage];
    NSDate *time = [[NSDate alloc]initWithTimeIntervalSince1970:conversation.latestMessage.timestamp];

    [cell.image sd_setImageWithURL:[NSURL URLWithString:info.avatar]];
    cell.title.text = info.nickname;
    cell.time.text = [Tool dateWithDateFormat:@"MM月dd日" date:time];
    
    NSMutableString *str = conversation.unreadMessagesCount > 0 ? [[NSMutableString alloc]initWithFormat:@"[未读: %d条]  ",conversation.unreadMessagesCount] : [[NSMutableString alloc]init];
    switch (model.bodyType) {
        case EMMessageBodyTypeText:
            [str appendString:model.text];
            break;
        case EMMessageBodyTypeImage:
            [str appendString:@"[图片]"];
            break;
        case EMMessageBodyTypeVoice:
            [str appendString:@"[语音]"];
            break;
            
        default:
            break;
    }
    cell.subTitle.text = str;
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserInfo *info = self.dataArray[indexPath.row];
    SendMessageViewController *chatController = [[SendMessageViewController alloc] initWithConversationChatter:info.conversation.conversationId conversationType:EMConversationTypeChat];
    chatController.userInfo = info;
//    chatController.delegate = self;
//    chatController.dataSource = self;
    [self.navigationController pushViewController:chatController animated:YES];
}

-(NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WeakSelf(self)
    return @[[UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        EMConversation *conversation = [weakself.dataArray objectAtIndex:indexPath.row];
        [[EMClient sharedClient].chatManager deleteConversation:conversation.conversationId isDeleteMessages:YES completion:^(NSString *aConversationId, EMError *aError) {
           
            [weakself.dataArray removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationLeft)];
        }];
    }]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
